<template>
  <el-container class="main-container">
    <el-main class="content-area">
      <div class="favorites-page">
        <div class="header-nav">
          <el-button
              type="primary"
              icon="el-icon-back"
              @click="goBack"
              class="back-btn"
          >
            返回首页
          </el-button>
        </div>
        <h2 class="page-title">我的收藏</h2>
        <div v-if="favorites.length === 0" class="empty-tip">
          <el-empty description="暂无收藏书籍"></el-empty>
        </div>
        <div v-else class="book-list">
          <el-card
              v-for="book in favorites"
              :key="book.id"
              class="book-card"
              shadow="hover"
          >
            <div class="book-info">
              <h3>{{ book.title }}</h3>
              <p class="author">{{ book.author }}</p>
              <p class="price">¥ {{ book.price.toFixed(1) }}</p>
              <div class="action-buttons">
                <el-button
                    type="primary"
                    size="small"
                    @click="addToCart(book)"
                >
                  加入购物车
                </el-button>
                <el-button
                    type="danger"
                    size="small"
                    @click="removeFromFavorites(book)"
                    icon="el-icon-delete"
                >
                  移除
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script>
export default {
  name: 'FavoritesView',
  data() {
    return{
    favorites: JSON.parse(localStorage.getItem('favorites')) || []
    };
  },
  methods: {
    addToCart(book) {
      if (!this.$store.state.user) {
        this.$message.warning('请先登录');
        this.$router.push({
          path: '/login',
          query: { redirect: this.$route.fullPath }
        });
        return;
      }

      this.$message.success(`已添加《${book.title}》到购物车`);
      // 这里应该调用实际的加入购物车逻辑
    },
    removeFromFavorites(book) {
      const newFavorites = this.favorites.filter(b => b.id !== book.id);
      localStorage.setItem('favorites', JSON.stringify(newFavorites));
      this.$message.success(`已移除《${book.title}》`);
      this.$forceUpdate();
    },
    goBack() {
      if (window.history.length > 1) {
        this.$router.go(-1)
      } else {
        this.$router.push('/home')
      }
    },
  }
};
</script>

<style scoped>
.favorites-page {
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  text-align: center;
  margin-bottom: 30px;
  color: #2c3e50;
}

.empty-tip {
  text-align: center;
  margin-top: 50px;
}

.action-buttons {
  margin-top: 15px;
  display: flex;
  gap: 10px;
  justify-content: center;
}
.header-nav {
  margin-bottom: 20px;
}
</style>